package com.spring.raft.websocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.raft.service.RaftNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
public class WebSocketServer extends TextWebSocketHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Autowired
    private RaftNodeService raftNodeService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        System.out.println("✅ WebSocket 连接建立: " + session.getRemoteAddress());
        sessions.add(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("📩 收到消息: " + message.getPayload());
        var request = objectMapper.readValue(message.getPayload(), RaftNodeService.RaftRequest.class);
        raftNodeService.processRaftRequest(request);
    }

    public void broadcast(String message) throws Exception {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));
            }
        }
    }
}
